<script setup lang="ts">
import { reactive, Ref, ref } from "vue";
import { Router, useRouter, useRoute, RouteLocationNormalized } from "vue-router";
import { Lock, User } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { FormInstance } from "element-plus/es/components/form";
import { loginFormData } from "@/views/login/interface/interface.ts";
import useUserStore from "@/pinia/modules/user/userStore.ts";

const userStore = useUserStore();
const router: Router = useRouter();
const route: RouteLocationNormalized = useRoute();
/* 登录按钮的loading状态 */
const loading: Ref<boolean> = ref<boolean>(false);
/* el-form表单组件实例 */
const formRef = ref<FormInstance>();
/* 表单校验对象 */
const formRules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
  ],
});
/* 表单数据对象 */
const formData: loginFormData = reactive<loginFormData>({
  username: "admin",
  password: "atguigu123",
});
/* 登录按钮的回调函数 */
const handleLogin: () => Promise<void> = async (): Promise<void> => {
  const valid: boolean = await formRef.value?.validate(() => {
  }).catch((error: any) => error);
  if (!valid) return;
  try {
    loading.value = true;
    await userStore.login(formData);
    ElMessage.success("登录成功");
    const redirect_url: string = route.query.redirect_url as string;
    router.push(redirect_url || "/");
  } catch (error: any) {
    ElMessage.error(error.message);
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <el-card class="loginForm">
    <h1 class="title font">硅谷甄选后台管理系统</h1>
    <el-form :model="formData" :rules="formRules" ref="formRef">
      <el-form-item prop="username">
        <el-input placeholder="请输入用户名" v-model="formData.username" :prefix-icon="User"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input placeholder="请输入密码" v-model="formData.password" :prefix-icon="Lock" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped lang="scss">
.loginForm {
  width: 600px;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;

  :deep(.el-card__body) {
    width: 100%;
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    .el-form {
      width: 90%;

      .el-form-item__content {
        height: 40px;

        margin-bottom: 10px;

        .el-input {
          height: 100%;
        }
      }

      .el-button {
        width: 100%;
        height: 50px;
        font-size: 18px;
      }
    }

    h1 {
      text-align: center;
      font-size: 30px;
      margin-bottom: 50px;
      font-weight: 600;
      color: #001529;
    }

  }
}
</style>
